package com.apkcore.core.receiver

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log

// 自定义 BroadcastReceiver
class AppUpdateReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        if (Intent.ACTION_MY_PACKAGE_REPLACED == intent.action) {
            Log.d("AppUpdateReceiver", "应用更新成功")
            // 你可以在这里执行应用更新后的逻辑
            val launcherActivity = getLauncherActivity(context)
            if (launcherActivity != null) {
                // 启动当前应用的 Launcher Activity
                val mainActivityIntent = Intent().apply {
                    setClassName(context.packageName, launcherActivity)
                    flags = Intent.FLAG_ACTIVITY_NEW_TASK
                }
                context.startActivity(mainActivityIntent)
            }
//            context.startActivity(Intent(context, MainActivity::class.java).apply {
//                flags = Intent.FLAG_ACTIVITY_NEW_TASK
//            })
        }
    }

    private fun getLauncherActivity(context: Context): String? {
        val packageManager = context.packageManager
        val packageName = context.packageName

        val intent = Intent(Intent.ACTION_MAIN, null).apply {
            addCategory(Intent.CATEGORY_LAUNCHER)
        }

        val resolveInfos = packageManager.queryIntentActivities(intent, 0)
        for (resolveInfo in resolveInfos) {
            if (resolveInfo.activityInfo.packageName == packageName) {
                return resolveInfo.activityInfo.name
            }
        }
        return null
    }
}
